﻿import yaml
import shutil
import os
from loguru import logger

class Utils:

    @classmethod
    def get_yaml_data(cls, file_path):
        with open(file_path, "r", encoding="utf-8") as f:
            result = yaml.safe_load(f)
            datas = result.get("add").get("P1").get("datas")
            ids = result.get("add").get("P1").get("ids")
            return datas,ids

    @classmethod
    def clean_intermediate_files(cls, json_dir):
        """删除中间生成的JSON和TXT文件"""
        l = os.listdir(json_dir)
        print(l)
        for filename in os.listdir(json_dir):
            if filename.endswith(('.json', '.txt')):
                file_path = os.path.join(json_dir, filename)
                try:
                    if os.path.isfile(file_path):
                        os.unlink(file_path)
                    elif os.path.isdir(file_path):
                        shutil.rmtree(file_path)
                except Exception as e:
                    print(f"删除文件失败 {file_path}: {e}")

    @classmethod
    def clean_intermediate_folders(cls, *dir_paths):
        """递归删除指定文件夹及其内容"""
        for dir_path in dir_paths:
            if os.path.exists(dir_path):
                try:
                    shutil.rmtree(dir_path)  # 递归删除文件夹
                    print(f"已清理目录: {dir_path}")
                except Exception as e:
                    print(f"删除失败 {dir_path}: {e}")

    @classmethod
    def log_save_clean(cls, path):
        logger.add(path, rotation="10 MB", retention="1 days")

if __name__ == '__main__':
    r = Utils.get_yaml_data("../datas/add_info.yaml")
    Utils.clean_intermediate_folders("../tests/result/json")
    print()